package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);

        return addressList;
    }

    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId());
        addressMapper.insert(address);
    }

    @Override
    public void setDefault(Long id) {
        //修改当前用户的所有地址is_default=0
        Address address1 = new Address();
        address1.setIsDefault(0);
        //设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        addressMapper.update(address1, wrapper);

        //将指定记录的is_default设为1
        Address address2 = new Address();
        address2.setId(id);
        address2.setIsDefault(1);
        addressMapper.updateById(address2);
    }

    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault, 1);
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }

    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void delete(Long ids) {
        addressMapper.deleteById(ids);
    }
}
